// Tags: PersistedSegTree
#include <algorithm>
#include <cstdio>
#include <cstring>

typedef long long ll;

const int N = 1e5 + 5;
int n, m, cnt, a[N], rt[N];

struct Node {
  int ls, rs, siz;
} tr[N << 6];

inline void insert(int &x, int y, int l, int r, int p) {
  tr[x = ++cnt] = tr[y];
  ++tr[x].siz;
  if (l == r) return;
  int mid = (l + r) >> 1;
  if (p <= mid) insert(tr[x].ls, tr[y].ls, l, mid, p);
  else
    insert(tr[x].rs, tr[y].rs, mid + 1, r, p);
}

inline ll query(int x, int y, int l, int r, int L, int R) {
  if (L <= l && r <= R) return tr[y].siz - tr[x].siz;
  int mid = (l + r) >> 1;
  ll res = 0;
  if (L <= mid) res += query(tr[x].ls, tr[y].ls, l, mid, L, R);
  if (mid < R) res += query(tr[x].rs, tr[y].rs, mid + 1, r, L, R);
  return res;
}

inline ll solve(int v, int l, int r) {
  cnt = 0, rt[1] = 0;
  insert(rt[1], rt[1], 0, n << 1, n);
  int cnt = 0;
  ll res = 0;
  for (int i = 1; i <= n; i++) {
    cnt += a[i] <= v ? 1 : -1;
    insert(rt[i + 1], rt[i], 0, n << 1, cnt + n);
    res += query(rt[std::max(i - r, 0)], rt[std::max(i - l + 1, 0)], 0, n << 1,
                 0, cnt + n);
  }
  return res;
}

int main() {
#ifndef ONLINE_JUDGE
#ifdef LOCAL
  freopen("testdata.in", "r", stdin);
  freopen("testdata.out", "w", stdout);
#else
  freopen("x.in", "r", stdin);
  freopen("x.out", "w", stdout);
#endif
#endif

  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
  scanf("%d", &m);
  for (int l1, r1, l2, r2; m; --m) {
    scanf("%d%d%d%d", &l1, &r1, &l2, &r2);
    printf("%lld\n", solve(r1, l2, r2) - solve(l1 - 1, l2, r2));
  }
  return 0;
}